<template>
  <div>
    <el-dialog
      title="修改角色信息"
      :visible.sync="dialogFormVisible"
      @close="dialogClose"
    >
      <el-form ref="dataForm" v-model="selectedRole" style="text-align: left">
        <el-form-item label="角色权限" label-width="120px" prop="username">
          <el-input
            v-model="selectedRole.name"
            autocomplete="off"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="角色描述" label-width="120px" prop="name">
          <el-input v-model="selectedRole.nameZh" autocomplete="off" />
        </el-form-item>
        <el-form-item label="菜单栏配置" label-width="120px" prop="menus">
          <el-tree
            ref="tree"
            :data="menus"
            :props="props"
            show-checkbox
            node-key="id"
            accordion
            :default-checked-keys="defaultCheckedKeys"
            @check="handleCheckChange"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit(selectedRole)">确 定</el-button>
      </div>
    </el-dialog>
    <el-row style="margin: 18px 0px 0px 18px">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <!-- <el-breadcrumb-item :to="{ path: '/admin/dashboard' }" -->
        <el-breadcrumb-item>管理中心</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色配置</el-breadcrumb-item>
      </el-breadcrumb>
    </el-row>
    <role-create @onSubmit="listRoles()" />
    <el-card style="margin: 18px 2%; width: 95%">
      <el-table
        ref="multipleTable"
        :data="roles"
        stripe
        style="width: 100%"
        :max-height="700"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="id" width="100" />
        <el-table-column prop="name" label="角色权限" fit />
        <el-table-column prop="nameZh" label="角色描述" fit />
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enabled"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="(value) => commitStatusChange(value, scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="editRole(scope.$index, scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="handleDelete(scope.$index, scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 20px 0 20px 0; float: left">
        <el-button @click="delchoose">批量删除</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import RoleCreate from './RoleCreate'
export default {
  inject: ['reload'],
  name: 'UserRole',
  components: { RoleCreate },
  data() {
    return {
      dialogFormVisible: false,
      roles: [],
      menus: [],
      title: [],
      treeArr: [],
      id: [],
      selectedRole: [],
      // 默认选中节点的key
      defaultCheckedKeys: [],
      defaultCheckedParentKeys: [],
      defaultCheckedChildrenKeys: [],
      // 批量选中的数据
      multipleSelection: [],
      // 保存批量选中后的数据
      delarr: [],
      props: {
        id: 'id',
        label: 'title',
        children: 'children'
      }
    }
  },
  computed: {
    tableHeight() {
      return window.innerHeight - 320
    }
  },
  //  props: {
  //       id: "id",
  //       label: "nameZh",
  //       children: "children"
  //     }
  mounted() {
    this.listRoles()
    this.listMenus()
  },

  methods: {
    listRoles() {
      var _this = this
      this.$axios.get('/api/admin/role').then((resp) => {
        if (resp.status === 200) {
          _this.roles = resp.data.data
        }
      })
    },

    listMenus() {
      var _this = this
      this.$axios.get('/api/admin/role/menu').then((resp) => {
        if (resp.status === 200) {
          var arr = (_this.menus = resp.data.data)
          var arr
          for (let i = 0; i < arr.length; i++) {
            const element = arr[i].id
            this.defaultCheckedParentKeys.push(element)
          }
        }
      })
    },
    // 获取选中节点
    handleCheckChange() {
      // let res = this.$refs.tree
      //   .getCheckedKeys()
      //   .concat(this.$refs.tree.getHalfCheckedKeys());
      // let arr = [];
      // for (var i = 0; i < res.length; i++) {
      //   arr[i] = res[i];
      // }
      var a = this.$refs.tree
        .getCheckedKeys()
        .concat(this.$refs.tree.getHalfCheckedKeys())
      this.treeArr = JSON.parse(JSON.stringify(a))
    },
    commitStatusChange(value, role) {
      if (role.id !== 1) {
        this.$confirm('是否更改角色状态？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.$axios
              .put('/api/admin/role/status', {
                enabled: value,
                id: role.id
              })
              .then((resp) => {
                if (resp.status === 200) {
                  if (value) {
                    this.$message('角色 [' + role.nameZh + '] 已启用')
                    this.reload()
                  } else {
                    this.$message('角色 [' + role.nameZh + '] 已禁用')
                    this.reload()
                  }
                }
              })
          })
          .catch(() => {
            role.enabled = !role.enabled
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
      } else {
        role.enabled = true
        this.$alert('无法禁用系统管理员！')
      }
    },
    editRole(index, row) {
      this.dialogFormVisible = true
      if (this.dialogFormVisible) {
        // console.log(row.id);
        const _this = this
        const _id = row.id
        this.id = _id
        this.$axios
          .post('/api/admin/role/info', { id: _id })
          .then((res) => {
            this.selectedRole = res.data.data
          })
          .catch()

        this.$axios
          .post('/api/admin/role/rid', { id: _id })
          .then((resp) => {
            console.log(resp.data.data)
            if (resp.status == 200) {
              var arrs = resp.data.data
              const formatObj = arrs.reduce((pre, cur) => {
                return { ...pre, [cur['id']]: cur }
              }, {})
              var arr = []
              const formatArray = arrs.reduce((arr, cur) => {
                const pid = cur.pid ? cur.pid : 0
                const parent = formatObj[pid]
                if (parent) {
                  parent.children ? parent.children.push(cur) : (parent.children = [cur])
                } else {
                  arr.push(cur)
                }
                return arr
              }, [])

              console.log(formatArray)

              for (let i = 0; i < formatArray.length; i++) {
                const item = formatArray[i].children
                const ev = formatArray[i].id
                console.log(ev)
                if (item && item.length != 0) {
                  for (let j = 0; j < formatArray[i].children.length; j++) {
                    const element = formatArray[i].children[j].children
                    const ek = formatArray[i].children[j].id
                    if (element && element.length != 0) {
                      for (let k = 0; k < element.length; k++) {
                        const es = element[k].id
                        this.defaultCheckedKeys.push(es)
                      }
                    } else {
                      this.defaultCheckedKeys.push(ek)
                    }
                  }
                } else {
                  this.defaultCheckedKeys.push(ev)
                }
              }

              // 判断树是否已经加载，第一次打开对话框前树不存在，会报错。所以需要设置 default-checked
              if (this.$refs.tree) {
                this.$refs.tree.setCheckedKeys(this.defaultCheckedKeys)
              }
            }
          })
          .catch()
      }
    },

    dialogClose() {
      this.dialogFormVisible = false
      this.defaultCheckedKeys = []
      this.$nextTick(() => {
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedKeys([])
        }
      })
    },

    onSubmit(role) {
      if (this.dialogFormVisible) {
        console.log(this.ids)
        this.$axios
          .put('/api/admin/role', {
            id: role.id,
            name: role.name,
            nameZh: role.nameZh,
            enabled: role.enabled
          })
          .then((resp) => {
            if (resp.status === 200) {
              // this.$alert(resp.data.data);
              this.dialogFormVisible = false
              this.listRoles()
            }
          })

        this.$axios
          .post('/api/admin/role/change', { id: this.treeArr, rid: this.id })
          .then((res) => {
            if (res.status == 200) {
              this.selectedRole = res.data.data
              console.log(res.data.data)
            }
          })
          .catch()
      }
    },
    // 单条删除
    handleDelete(index, row) {
      console.log(row.id)
      const _id = row.id
      this.$axios
        .delete('/api/admin/role/del', { data: { id: _id }})
        .then((resp) => {
          // console.log(resp);
          if (resp.status === 200) {
            this.$message.success(resp.data.data)
            this.reload()
          }
        })
        .catch((error) => {
          this.$message.error(error.response.error)
          this.reload()
        })
    },
    // 得到选中数据
    handleSelectionChange(val) {
      const a = (this.multipleSelection = val)
      // console.log(a);
      const resdata = JSON.parse(JSON.stringify(this.multipleSelection))
      // console.log("运行记录组件接到的数据", resdata);
      const b = Object.assign({}, a)
      this.delall = b
    },
    // 批量删除
    delchoose() {
      // 监听选中框的个数，定义变量承载选中的个数
      const length = this.multipleSelection.length
      if (length < 2) {
        this.$message.error('请至少选择两条数据')
      } else {
        for (let i = 0; i < length; i++) {
          // console.log(this.multipleSelection[i])
          this.delarr.push(this.multipleSelection[i].id)
          console.log(this.delarr[i])
        }
        // let resdata = JSON.parse(JSON.stringify(this.delarr));
        const resdata = JSON.stringify(this.delarr)
        console.log(resdata)
        this.$axios
          .delete('/api/admin/role/delMore', {
            params: {
              users: this.delarr
            },
            paramsSerializer: (params) => {
              return this.$qs.stringify(params, { indices: false })
            }
          })
          .then((resp) => {
            // console.log(resp);
            if (resp.status === 200) {
              this.$message.success(resp.data.data)
              this.reload()
            }
          })
          .catch((error) => {
            this.$message.error(error.response.error)
            this.reload()
          })
      }
    }
  }
}
</script>

<style scoped>
.add-button {
  float: left;
  margin: 18px 0 18px 10px;
}
</style>
